<template>
  <div>
    <el-form :inline="true" :model="queryMode" class="demo-form-inline" >
      <el-form-item label="负责人" >
        <el-select
            v-model="queryMode.ownerId"
            clearable
            placeholder="请选择负责人"
            style="width: 240px"
        >
          <el-option
              v-for="item in userSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="活动名称">
        <el-input v-model="queryMode.name" placeholder="请选择活动名称"/>
      </el-form-item>

      <el-form-item label="开始时间" prop="startDate" >
        <el-date-picker
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="queryMode.startDate"
            type="datetime"
            placeholder="请选择活动开始时间"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endDate" >
        <el-date-picker
            v-model="queryMode.endDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择活动结束时间"
        />
      </el-form-item>

      <el-form-item label="活动预算" prop="cost" >
        <el-input v-model="queryMode.cost" placeholder="请输入您的活动预算"/>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime" >
        <el-date-picker
            v-model="queryMode.createTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择活动开始时间"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="querySelect">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="mb-4">
    <el-button type="success" class="edit" @click="addActivity">录入市场活动</el-button>
    <el-button type="danger" class="edit" @click="batchDelActivity">批量删除</el-button>
  </div>

  <!--弹窗  -->
  <el-dialog v-model="dialogFormVisible" :title="activityQuery.id > 0 ? '编辑市场活动':'录入市场活动'" width="600" >
    <el-form :model="activityQuery" :rules="dialogFormRules" ref="dialogRef">
      <el-form-item label="负责人" prop="ownerId" >
         <el-select
          v-model="activityQuery.ownerId"
          clearable
          placeholder="请选择负责人"
          style="width: 240px"
      >
        <el-option
            v-for="item in userSelect"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
      </el-form-item>


      <el-form-item label="活动名称" prop="name" >
        <el-input v-model="activityQuery.name" />
      </el-form-item>

      <el-form-item label="开始时间" prop="startDate" >
        <el-date-picker
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="activityQuery.startDate"
            type="datetime"
            placeholder="请选择活动开始时间"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endDate" >
        <el-date-picker
            v-model="activityQuery.endDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择活动结束时间"
        />
      </el-form-item>

      <el-form-item label="预算" prop="cost" >
        <el-input v-model="activityQuery.cost" />
      </el-form-item>

      <el-form-item label="活动描述" prop="description" >
        <el-input type="textarea" v-model="activityQuery.description" />
      </el-form-item>


    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitActivity">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>



  <el-table :data="marketActivityList"
            style="width: 100%"
            @selection-change="selectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="80"/>
    <el-table-column property="ownerName" label="负责人" width="80"/>
    <el-table-column property="name" label="活动名称" />
    <el-table-column property="startDate" label="开始时间" show-overflow-tooltip/>
    <el-table-column property="endDate" label="结束时间" show-overflow-tooltip/>
    <el-table-column property="description" label="活动描述" width="200"/>
    <el-table-column property="cost" label="预算"/>
    <el-table-column property="createTime" label="创建时间" show-overflow-tooltip/>
    <el-table-column label="操作">
      <!--使用插槽获取用户信息-->
      <template #default="scope">
        <el-button type="primary" @click="details(scope.row.id)">详情</el-button>
        <el-button type="success" @click="editUser(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="delActivity(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <p></p>
  <p></p>
  <p></p>
  <el-pagination
      class="page"
      background
      :page-size=pageSize
      layout="prev, pager, next"
      @current-change="page"
      @prev-click="page"
      @next-click="page"
      :total=total />
</template>

<script >
import {confirmMessageTip, messageTip} from "@/util/utils";
import {doDelete, doGet, doPost, doPut} from "@/http/httpRequest";

export default {
  name:"MarketActivityView",
  data(){
    return{
      marketActivityList:[],
      pageSize:0,
      total:0,
      current:1,
      dialogFormVisible:false,
      activityQuery:{},
      userSelect:[],
      dialogFormRules:{
        ownerId: [
            {required:true, message: "请输入", trigger:'blur'}
        ],
        name: [
          {required:true, message: "请输入", trigger:'blur'}
        ],
        startDate: [
          {required:true, message: "请输入", trigger:'blur'}
        ],
        endDate: [
          {required:true, message: "请输入", trigger:'blur'},
          {validator: this.endDateCheck, trigger:'blur'}
        ],
        cost: [
          {required:true, message: "请输入", trigger:'blur'},
        ],
        description: [
          {required:true, message: "请输入活动描述", trigger:'blur'}
        ],
      },
      activityIdArray:[],
      queryMode:{},
    }
  },

  //父页面的函数使用
  inject:['reload'],
  methods:{
    /**
     * 重置
     */
    reset(){
      this.queryMode = {};
      this.reload();
    },

    //多选框的方法
    selectionChange(dataArray){
      this.activityIdArray = [],
          dataArray.forEach(data =>{
            this.activityIdArray.push(data.id)
          })
      console.log(this.activityIdArray);
    },

    //条件分页查询
    querySelect(){
      this.doSelect()
    },
    //条件分页查询
    doSelect(current){
      if (current === undefined){
        current = 1;
      }
      doGet("api/queryPage",{
        current:current,
        ownerId:this.queryMode.ownerId,
        name:this.queryMode.name,
        startDate:this.queryMode.startDate,
        endDate:this.queryMode.endDate,
        cost:this.queryMode.cost,
        createTime:this.queryMode.createTime,
      }).then(res =>{
        if (res.data.code === 200){
          this.marketActivityList = res.data.data.list;
          this.pageSize = res.data.data.pageSize;
          this.total = res.data.data.total;
        }
      })
    },
    /**
     *
     */
    batchDelActivity() {
      if (this.activityIdArray.length === 0) {
        messageTip("请选择需要删除的用户！", "warning");
      } else {
        confirmMessageTip("确定删除这些活动吗？").then(() => {
          let activityIds = this.activityIdArray.join(",")
          doDelete("api/batchDelActivity", {activityIds:activityIds}).then(res =>{
            if (res.data.code === 200) {
              messageTip("删除成功")
              this.reload()
            }else {
              messageTip("批量删除失败，原因是" + res.data.msg,"error")
              this.reload()
            }
          })
        }) .catch(()=>{
          messageTip("操作取消", "warning")
        })
      }
    },


    /**
     * 录入|更新市场活动的提交
     */
    submitActivity(){
      this.$refs.dialogRef.validate(vaild =>{
        if (vaild){
          if (this.activityQuery.id > 0){
            //更新活动
            doPut("api/updateActivity",this.activityQuery).then(res =>{
              if (res.data.code === 200 ){
                messageTip("更新市场活动成功", "success"),
                    this.reload();
              }
            })
          }
          //console.log(JSON.stringify(this.activityQuery))
          doPost("api/addActivity",this.activityQuery).then(res =>{
            //添加活动
            if (res.data.code === 200 ){
              messageTip("添加市场活动成功", "success"),
              this.reload();
            }
          })
        }
      })
    },
    /**
     * 关于结束日期的错误检查
     * @param rule
     * @param value
     * @param callback
     */
    endDateCheck(rule , value, callback){
      if (value < this.activityQuery.startDate){
        callback(new Error("请检查有效日期"));
      }else {
        callback();
      }
    },
    /**
     * //加载市场活动信息
     * @param current
     */
    loadMarketActivity(current){
      doGet("api/marketActivity",{
        current:current
      }).then(res =>{
        if (res.data.code === 200){
          this.marketActivityList = res.data.data.list;
          this.pageSize = res.data.data.pageSize;
          this.total = res.data.data.total;
        }
      })
    },
    /**
     * 加载下拉框选项
     */
    loadUserSelect(){
      //加载负责人
      doGet("api/loadUserSelect",{}).then(res =>{
        if (res.data.code === 200) {
          this.userSelect = res.data.data;
        }else {
          messageTip("加载负责人下拉选项失败","error")
        }
      })
    },

    /**
     * 分页
     * @param current
     */
    page(current){
      //console.log(current === null)
      if (Object.keys(this.queryMode).length === 0){
        this.loadMarketActivity(current);
      }else {
        this.doSelect(current);
      }
    },
    details(id) {
      //跳转路由
      this.$router.push('/hello/marketActivity/' + id)
    },
    editUser(activityId){
      //编辑，新增共用一个弹窗。
      this.dialogFormVisible = true;
      //获取用户信息
      this.activityDetail(activityId);
    },

    /**
     * 获取活动详情
     * @param activityId
     */
    activityDetail(activityId){
      doGet("api/activityDetail/" + activityId, {}).then(res =>{
        if (res.data.code === 200) {
          this.activityQuery = res.data.data;
        }
      })
    },
    /**
     * 添加市场活动
     */
    addActivity(){
      this.activityQuery = {};
      this.dialogFormVisible = true;
    },
    /**
     * 删除用户
     * @param userId
     */
    delActivity(activityId) {
      confirmMessageTip('确认删除此用户吗？').then(() => {
        //删除用户
        doDelete("api/delActivity/" + activityId,{}).then(res =>{
          if (res.data.code === 200) {
            messageTip("删除成功", "success")
            //刷新
            this.reload();
          }else {
            messageTip(res.data.msg,"error")
          }
        })
      }).catch(() => {
        messageTip("取消", "info")
      })
    },


  },
  mounted() {
    this.loadMarketActivity(1);
    this.loadUserSelect();
  }
}

</script>



<style scoped>
.edit{
  margin-bottom: 15px;
}
.page{
  display: flex;
  justify-content: center;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

</style>